<template>
  <div class="pdf-viewer-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <p>正在加载PDF文档...</p>
      </div>
    </div>
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <div class="error-content">
        <h3>PDF加载失败</h3>
        <p>{{ errorMessage }}</p>
        <button @click="retryLoad" class="retry-btn">重新加载</button>
        <button @click="goBack" class="back-btn">返回</button>
      </div>
    </div>
    <!-- PDF阅读器 -->
    <div v-else class="pdf-reader">
      <!-- 顶部工具栏 -->
      <div class="top-toolbar">
        <!-- 左侧菜单按钮 -->
        <div class="toolbar-left">
          <button @click="toggleSidebar" class="menu-btn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
            </svg>
          </button>
          <span class="pdf-info">{{ title || 'PDF文档' }}</span>
        </div>
        <!-- 中间导航控制 -->
        <div class="toolbar-center">
          <button @click="scrollToPrevPage" class="nav-btn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
            </svg>
          </button>
          <div class="page-controls">
            <input
                v-model="pageInput"
                @keyup.enter="scrollToPage"
                @blur="scrollToPage"
                class="page-input"
                type="number"
                :min="1"
                :max="totalPages"
            />
            <span class="page-separator">/</span>
            <span class="total-pages">{{ totalPages }}</span>
          </div>
          <button @click="scrollToNextPage" class="nav-btn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
            </svg>
          </button>
          <div class="zoom-controls">
            <button @click="zoomOut" class="zoom-btn">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M19 13H5v-2h14v2z"/>
              </svg>
            </button>
            <span class="zoom-display">{{ Math.round(scale * 100) }}%</span>
            <button @click="zoomIn" class="zoom-btn">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
              </svg>
            </button>
          </div>
        </div>
        <!-- 右侧工具按钮 -->
        <div class="toolbar-right">
          <button
              @click="toggleInfoPanel"
              class="tool-icon"
              :title="showInfoPanel ? `隐藏${contentTypeConfig.name}信息` : `显示${contentTypeConfig.name}信息`"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
            </svg>
          </button>
          <button @click="fitToWidth" class="tool-icon" :title="isFitToWidth ? '恢复100%' : '适合页面宽度'">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
            </svg>
          </button>
          <button @click="resetScale" class="tool-icon" title="重置缩放">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/>
            </svg>
          </button>
          <button @click="rotatePage" class="tool-icon" title="旋转页面90°">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6z"/>
            </svg>
          </button>
          <button @click="downloadPdf" class="tool-icon" title="下载文件">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
            </svg>
          </button>
          <button @click="goBack" class="tool-icon" title="返回">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
            </svg>
          </button>
        </div>
      </div>
      <!-- 主要内容区域 -->
      <div class="main-content" ref="mainContent">
        <!-- 左侧面板 -->
        <div v-show="showSidebar" class="sidebar-panel">
          <!-- 动态信息面板 -->
          <div v-show="showInfoPanel" class="content-info-panel">
            <div class="content-info-header">
              <h3>{{ contentTypeConfig.name }}信息</h3>
              <button @click="toggleThumbnails" class="toggle-btn">
                {{ showThumbnails ? '隐藏缩略图' : '显示缩略图' }}
              </button>
            </div>
            <!-- 动态组件渲染 -->
            <component
                :is="contentTypeConfig.component"
                :info="contentInfo"
            />
          </div>
          <!-- 缩略图面板 -->
          <div v-show="showThumbnails" class="thumbnails-container">
            <div class="thumbnails-header">
              <h4>页面缩略图</h4>
            </div>
            <div class="thumbnails-list">
              <div
                  v-for="(imageUrl, index) in pdfImageUrls"
                  :key="index + 1"
                  :class="['thumbnail-item', { active: (index + 1) === currentPage }]"
                  @click="scrollToPageNumber(index + 1)"
              >
                <div class="thumbnail-wrapper">
                  <img
                      :src="imageUrl"
                      class="thumbnail-image"
                      :alt="`页面 ${index + 1}`"
                      @error="handleImageError"
                  />
                </div>
                <div class="thumbnail-page-number">{{ index + 1 }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 中间分隔线 -->
        <div v-show="showSidebar" class="sidebar-divider"></div>
        <!-- PDF内容区域 - 连续滚动 -->
        <div class="pdf-content-area" ref="pdfContentArea" @scroll="handleScroll">
          <div class="pdf-pages-container" ref="pdfContainer">
            <div
                v-for="(imageUrl, index) in pdfImageUrls"
                :key="index + 1"
                :ref="(el) => setPageRef(el, index + 1)"
                class="pdf-page-wrapper"
                :data-page="index + 1"
            >
              <div class="pdf-page-image-container" :style="getPageStyle()">
                <img
                    :src="imageUrl"
                    class="pdf-page-image"
                    :alt="`PDF页面 ${index + 1}`"
                    :style="getImageStyle()"
                    @error="handleImageError"
                    @load="handleImageLoad"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, computed, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getPdfImageUrls } from '@/api/Manage/File.js'
import {getPaperById, paperApi} from '@/api/Manage/paper.js'
import { getPatentById } from '@/api/Manage/patent.js'
import { getCopyRightById } from '@/api/Manage/software.js'
import { getPersonalAwardById } from '@/api/Manage/personalAward.js'
import { getStudentAwardById } from '@/api/Manage/studentAward.js'
import { getContinueEducationById } from '@/api/Manage/continueEducation.js'
import { getPublicationById } from '@/api/Manage/publication.js'
import { getReportById } from '@/api/Manage/report.js'
import { getCertificationById } from '@/api/Manage/Certification.js'
import { getOtherById } from '@/api/Manage/other.js'
import { getHorizontalById } from '@/api/Research/Horizontal.js'
import { getLongitudinalById } from '@/api/Research/Longitudinal.js'
import PaperInfoPanel from '@/components/info-panels/PaperInfoPanel.vue'
import PatentInfoPanel from '@/components/info-panels/PatentInfoPanel.vue'
import SoftwareInfoPanel from "@/components/info-panels/SoftwareInfoPanel.vue";
import PersonalAwardInfoPanel from "@/components/info-panels/PersonalAwardInfoPanel.vue";
import StudentAwardInfoPanel from "@/components/info-panels/StudentAwardInfoPanel.vue";
import ContinueEducationInfoPanel from "@/components/info-panels/ContinueEducationInfoPanel.vue";
import PublicationInfoPanel from "@/components/info-panels/PublicationInfoPanel.vue";
import ReportInfoPanel from "@/components/info-panels/ReportInfoPanel.vue";
import CertificationInfoPanel from "@/components/info-panels/CertificationInfoPanel.vue";
import OtherInfoPanel from "@/components/info-panels/OtherInfoPanel.vue";
import HorizontalInfoPanel from "@/components/info-panels/HorizontalInfoPanel.vue";
import LongitudinalInfoPanel from "@/components/info-panels/LongitudinalInfoPanel.vue";

// 使用 Composition API
const route = useRoute()
const router = useRouter()

// 响应式数据
const pdfUrl = ref('')
const title = ref('')
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')
const showSidebar = ref(true)
const showInfoPanel = ref(true)
const showThumbnails = ref(true)
const isFitToWidth = ref(false)

// PDF相关
const pdfImageUrls = ref([])
const currentPage = ref(1)
const totalPages = ref(0)
const scale = ref(1.0) // 改为1.0作为基准
const pageInput = ref(1)
const rotation = ref(0)

// 内容类型和信息
const contentType = ref('paper') // 默认为论文
const contentInfo = ref({})

// DOM引用
const pdfContentArea = ref(null)
const pdfContainer = ref(null)
const mainContent = ref(null)
const pageRefs = ref(new Map())

// 页面尺寸管理
const maxPageWidth = ref(800)
const maxPageHeight = ref(1200)

// 内容类型配置
const contentTypeConfigs = {
  paper: {
    name: '论文',
    component: PaperInfoPanel,
    api: getPaperById,
    formatData: (data) => {
      if (data.publishDate) {
        const date = new Date(data.publishDate)
        data.publishDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  patent: {
    name: '专利',
    component: PatentInfoPanel,
    api: getPatentById,
    formatData: (data) => {
      if (data.applicationDate) {
        const date = new Date(data.applicationDate)
        data.applicationDate = date.toISOString().split('T')[0]
      }
      if (data.authorizationDate) {
        const date = new Date(data.authorizationDate)
        data.authorizationDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  software: {
    name: '软件著作',
    component: SoftwareInfoPanel,
    api: getCopyRightById,
    formatData: (data) => {
      if (data.applicationDate) {
        const date = new Date(data.applicationDate)
        data.applicationDate = date.toISOString().split('T')[0]
      }
      if (data.registrationDate) {
        const date = new Date(data.registrationDate)
        data.registrationDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  personalAward: {
    name: '个人获奖',
    component: PersonalAwardInfoPanel,
    api: getPersonalAwardById,
    formatData: (data) => {
      if (data.awardDate) {
        const date = new Date(data.awardDate)
        data.awardDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  studentAward: {
    name: '学生获奖',
    component: StudentAwardInfoPanel,
    api: getStudentAwardById,
    formatData: (data) => {
      if (data.awardDate) {
        const date = new Date(data.awardDate)
        data.awardDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  continueEducation: {
    name: '继续教育',
    component: ContinueEducationInfoPanel,
    api: getContinueEducationById,
    formatData: (data) => {
      if (data.startDate) {
        const date = new Date(data.startDate)
        data.startDate = date.toISOString().split('T')[0]
      }
      if (data.endDate) {
        const date = new Date(data.endDate)
        data.endDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  publication: {
    name: '著作',
    component: PublicationInfoPanel,
    api: getPublicationById,
    formatData: (data) => {
      if (data.publishDate) {
        const date = new Date(data.publishDate)
        data.publishDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  report: {
    name: '新闻报道',
    component: ReportInfoPanel,
    api: getReportById,
    formatData: (data) => {
      if (data.publishDate) {
        const date = new Date(data.publishDate)
        data.publishDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  certification: {
    name: '档案资料',
    component: CertificationInfoPanel,
    api: getCertificationById,
    formatData: (data) => {
      if (data.issueDate) {
        const date = new Date(data.issueDate)
        data.issueDate = date.toISOString().split('T')[0]
      }
      if (data.expiryDate) {
        const date = new Date(data.expiryDate)
        data.expiryDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  other: {
    name: '其他成果',
    component: OtherInfoPanel,
    api: getOtherById,
    formatData: (data) => data
  },
  // 新增：横向项目配置
  horizontal: {
    name: '横向项目',
    component: HorizontalInfoPanel, // 对应横向项目的展示组件
    api: getHorizontalById, // 横向项目的接口
    formatData: (data) => {
      // 假设横向项目有以下日期字段，根据实际接口返回调整
      if (data.startDate) {
        const date = new Date(data.startDate)
        data.startDate = date.toISOString().split('T')[0]
      }
      if (data.endDate) {
        const date = new Date(data.endDate)
        data.endDate = date.toISOString().split('T')[0]
      }
      if (data.signDate) { // 签约日期
        const date = new Date(data.signDate)
        data.signDate = date.toISOString().split('T')[0]
      }
      return data
    }
  },
  longitudinal: {
    name: '纵向项目',
    component: LongitudinalInfoPanel, // 对应纵向项目的展示组件
    api: getLongitudinalById, // 纵向项目的接口
    formatData: (data) => {
      // 假设纵向项目有以下日期字段，根据实际接口返回调整
      if (data.approvalDate) { // 立项日期
        const date = new Date(data.approvalDate)
        data.approvalDate = date.toISOString().split('T')[0]
      }
      if (data.conclusionDate) { // 结题日期
        const date = new Date(data.conclusionDate)
        data.conclusionDate = date.toISOString().split('T')[0]
      }
      return data
    }
  }
}

// 计算当前内容类型配置
const contentTypeConfig = computed(() => {
  return contentTypeConfigs[contentType.value] || contentTypeConfigs.paper
})

// 设置页面引用
const setPageRef = (el, pageNum) => {
  if (el) {
    pageRefs.value.set(pageNum, el)
  }
}

// 初始化PDF阅读器
const initializePdfViewer = async () => {
  try {
    const urlParam = route.query.pdfUrl
    const titleParam = route.query.title
    const typeParam = route.query.type || 'paper'
    const idParam = route.query.id

    if (!urlParam) {
      throw new Error('缺少PDF文件路径')
    }

    pdfUrl.value = decodeURIComponent(urlParam)
    title.value = titleParam ? decodeURIComponent(titleParam) : 'PDF文档'
    contentType.value = typeParam

    // 如果有ID，获取详细信息
    if (idParam) {
      await loadContentInfo(idParam)
    }

    await loadPdfImages()
  } catch (err) {
    console.error('初始化PDF阅读器失败:', err)
    error.value = true
    errorMessage.value = err.message
    loading.value = false
  }
}

// 加载内容信息
const loadContentInfo = async (id) => {
  try {
    const config = contentTypeConfig.value
    const response = await config.api(id)
    if (response.code === 1 && response.data) {
      contentInfo.value = config.formatData(response.data)
      console.log('contentInfo', contentInfo.value)
    }
  } catch (err) {
    console.warn(`加载${contentTypeConfig.value.name}信息失败:`, err)
  }
}

// 加载PDF图片
const loadPdfImages = async () => {
  try {
    loading.value = true
    const response = await getPdfImageUrls(pdfUrl.value)
    console.log("response", response)
    if (response.code === '0' && response.data && response.data.imageUrls && response.data.imageUrls.length > 0) {
      pdfImageUrls.value = response.data.imageUrls
      totalPages.value = response.data.pageCount || response.data.imageUrls.length
      loading.value = false
      await nextTick()
      await preloadFirstImage()
    } else {
      throw new Error('PDF转换失败或没有返回图片数据')
    }
  } catch (err) {
    console.error('PDF图片加载失败:', err)
    error.value = true
    errorMessage.value = 'PDF文件处理失败，请检查文件是否正确'
    loading.value = false
  }
}

// 预加载第一页图片获取尺寸
const preloadFirstImage = () => {
  return new Promise((resolve) => {
    if (pdfImageUrls.value.length === 0) {
      resolve()
      return
    }
    const img = new Image()
    img.onload = () => {
      maxPageWidth.value = img.naturalWidth
      maxPageHeight.value = img.naturalHeight

      // 自动计算合适的缩放比例
      autoFitScale()

      resolve()
    }
    img.onerror = () => {
      resolve()
    }
    img.src = pdfImageUrls.value[0]
  })
}

// 新增：自动适应缩放函数
const autoFitScale = () => {
  if (!mainContent.value || !maxPageWidth.value || !maxPageHeight.value) return

  // 获取容器尺寸，预留边距
  const sidebarWidth = showSidebar.value ? 280 : 0
  const containerWidth = mainContent.value.clientWidth - sidebarWidth - 80 // 左右各40px边距
  const containerHeight = window.innerHeight - 200 // 减去工具栏和其他元素高度

  // 计算基于宽度和高度的缩放比例
  const scaleByWidth = containerWidth / maxPageWidth.value
  const scaleByHeight = containerHeight / maxPageHeight.value

  // 选择较小的缩放比例，确保PDF完整显示
  let autoScale = Math.min(scaleByWidth, scaleByHeight)

  // 限制缩放范围：最小0.3，最大2.0
  autoScale = Math.max(0.3, Math.min(2.0, autoScale))

  // 如果计算出的缩放比例太小（小于0.6），适当放大以保证可读性
  if (autoScale < 0.6) {
    autoScale = Math.min(0.8, scaleByWidth) // 优先保证宽度适应
  }

  scale.value = autoScale
  console.log(`自动缩放: 原始尺寸 ${maxPageWidth.value}x${maxPageHeight.value}, 容器尺寸 ${containerWidth}x${containerHeight}, 缩放比例 ${autoScale}`)
}

// 获取页面容器样式
const getPageStyle = () => {
  const containerWidth = maxPageWidth.value * scale.value
  const containerHeight = maxPageHeight.value * scale.value
  return {
    width: `${containerWidth}px`,
    height: `${containerHeight}px`,
    transform: `rotate(${rotation.value}deg)`,
    transformOrigin: 'center center'
  }
}

// 获取图片样式
const getImageStyle = () => {
  return {
    width: '100%',
    height: '100%',
    objectFit: 'contain'
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  console.warn('图片加载失败:', event.target.src)
  event.target.style.display = 'none'
}

// 处理图片加载完成
const handleImageLoad = (event) => {
  event.target.style.opacity = '1'
}

// 处理滚动事件
const handleScroll = () => {
  if (!pdfContentArea.value) return
  const scrollTop = pdfContentArea.value.scrollTop
  const containerHeight = pdfContentArea.value.clientHeight

  for (let pageNum = 1; pageNum <= totalPages.value; pageNum++) {
    const pageElement = pageRefs.value.get(pageNum)
    if (!pageElement) continue

    const rect = pageElement.getBoundingClientRect()
    const containerRect = pdfContentArea.value.getBoundingClientRect()
    const pageCenter = rect.top + rect.height / 2 - containerRect.top
    const viewportCenter = containerHeight / 2

    if (Math.abs(pageCenter - viewportCenter) < rect.height / 2) {
      if (currentPage.value !== pageNum) {
        currentPage.value = pageNum
        pageInput.value = pageNum
      }
      break
    }
  }
}

// 滚动到指定页面
const scrollToPageNumber = (pageNum) => {
  const pageElement = pageRefs.value.get(pageNum)
  if (pageElement && pdfContentArea.value) {
    pageElement.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

const scrollToPrevPage = () => {
  if (currentPage.value > 1) {
    scrollToPageNumber(currentPage.value - 1)
  }
}

const scrollToNextPage = () => {
  if (currentPage.value < totalPages.value) {
    scrollToPageNumber(currentPage.value + 1)
  }
}

const scrollToPage = () => {
  const pageNum = parseInt(pageInput.value)
  if (pageNum >= 1 && pageNum <= totalPages.value) {
    scrollToPageNumber(pageNum)
  } else {
    pageInput.value = currentPage.value
  }
}

// 缩放控制
const zoomIn = () => {
  scale.value = Math.min(scale.value * 1.2, 3)
  isFitToWidth.value = false
}

const zoomOut = () => {
  scale.value = Math.max(scale.value / 1.2, 0.1)
  isFitToWidth.value = false
}

// 适合页面宽度
const fitToWidth = () => {
  if (!pdfContainer.value || !maxPageWidth.value) return

  if (isFitToWidth.value) {
    // 恢复自动缩放
    autoFitScale()
    isFitToWidth.value = false
  } else {
    const containerWidth = pdfContainer.value.clientWidth - 40
    const newScale = containerWidth / maxPageWidth.value
    scale.value = Math.max(Math.min(newScale, 3), 0.5)
    isFitToWidth.value = true
  }
}

// 重置缩放到自动适应大小
const resetScale = () => {
  autoFitScale()
  isFitToWidth.value = false
}

// 旋转页面
const rotatePage = () => {
  rotation.value = (rotation.value + 90) % 360
}

// 切换侧边栏
const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value
  // 侧边栏切换后重新计算缩放
  setTimeout(() => {
    if (maxPageWidth.value && maxPageHeight.value) {
      autoFitScale()
    }
  }, 300)
}

// 切换信息面板
const toggleInfoPanel = () => {
  showInfoPanel.value = !showInfoPanel.value
}

// 切换缩略图
const toggleThumbnails = () => {
  showThumbnails.value = !showThumbnails.value
}

// 重新加载
const retryLoad = () => {
  loading.value = true
  error.value = false
  errorMessage.value = ''
  initializePdfViewer()
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 下载PDF文件
const downloadPdf = () => {
  const link = document.createElement('a')
  link.href = pdfUrl.value
  link.download = title.value + '.pdf'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 添加窗口大小变化处理函数
const handleWindowResize = () => {
  // 延迟执行，避免频繁计算
  clearTimeout(window.resizeTimer)
  window.resizeTimer = setTimeout(() => {
    if (maxPageWidth.value && maxPageHeight.value) {
      autoFitScale()
    }
  }, 300)
}

// 生命周期钩子
onMounted(() => {
  initializePdfViewer()

  // 监听窗口大小变化
  window.addEventListener('resize', handleWindowResize)
})

// 在组件卸载时清理监听器
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleWindowResize)
  clearTimeout(window.resizeTimer)
})

// 监听器
watch(currentPage, (newPage) => {
  pageInput.value = newPage
})
</script>

<style scoped>
.pdf-viewer-container {
  width: 100vw;
  height: 100vh;
  background: #323639;
  color: #e8eaed;
  font-family: 'Roboto', 'Arial', sans-serif;
  overflow: hidden;
}

.loading-container, .error-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #323639;
  z-index: 999;
}

.loading-spinner {
  text-align: center;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #555;
  border-top: 4px solid #1a73e8;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-content {
  text-align: center;
  padding: 40px;
  background: #3c4043;
  border-radius: 8px;
}

.retry-btn, .back-btn {
  padding: 8px 16px;
  margin: 0 8px;
  border: 1px solid #5f6368;
  border-radius: 4px;
  background: #3c4043;
  color: #e8eaed;
  cursor: pointer;
  font-size: 14px;
}

.retry-btn:hover, .back-btn:hover {
  background: #48494a;
}

/* PDF阅读器 */
.pdf-reader {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部工具栏 */
.top-toolbar {
  height: 48px;
  background: #323639;
  border-bottom: 1px solid #5f6368;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.menu-btn {
  background: transparent;
  border: none;
  color: #e8eaed;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-btn:hover {
  background: #48494a;
}

.pdf-info {
  font-size: 14px;
  color: #e8eaed;
  font-weight: 400;
}

.toolbar-center {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-left: 300px;
}

.nav-btn {
  background: transparent;
  border: none;
  color: #e8eaed;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-btn:hover {
  background: #48494a;
}

.page-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-input {
  width: 40px;
  background: #3c4043;
  border: 1px solid #5f6368;
  color: #e8eaed;
  text-align: center;
  padding: 4px 6px;
  border-radius: 4px;
  font-size: 13px;
}

.page-input:focus {
  outline: none;
  border-color: #1a73e8;
}

.page-separator, .total-pages {
  font-size: 13px;
  color: #9aa0a6;
}

.zoom-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.zoom-btn {
  background: transparent;
  border: none;
  color: #e8eaed;
  padding: 6px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.zoom-btn:hover {
  background: #48494a;
}

.zoom-display {
  font-size: 13px;
  color: #e8eaed;
  min-width: 45px;
  text-align: center;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 4px;
}

.tool-icon {
  background: transparent;
  border: none;
  color: #e8eaed;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tool-icon:hover {
  background: #48494a;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧面板 */
.sidebar-panel {
  width: 280px;
  background: #323639;
  flex-shrink: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

/* 内容信息面板 */
.content-info-panel {
  flex-shrink: 0;
  border-bottom: 1px solid #5f6368;
}

.content-info-header {
  padding: 16px;
  border-bottom: 1px solid #5f6368;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-info-header h3 {
  margin: 0;
  font-size: 16px;
  color: #e8eaed;
}

.toggle-btn {
  background: transparent;
  border: 1px solid #5f6368;
  color: #e8eaed;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.toggle-btn:hover {
  background: #48494a;
}

/* 缩略图面板 */
.thumbnails-container {
  flex: 1;
  overflow-y: auto;
}

.thumbnails-header {
  padding: 16px;
  border-bottom: 1px solid #5f6368;
}

.thumbnails-header h4 {
  margin: 0;
  font-size: 14px;
  color: #e8eaed;
}

.thumbnails-list {
  padding: 16px 8px;
}

.thumbnail-item {
  margin-bottom: 16px;
  cursor: pointer;
  text-align: center;
}

.thumbnail-wrapper {
  border: 3px solid transparent;
  border-radius: 2px;
  padding: 2px;
  background: #48494a;
  margin-bottom: 4px;
}

.thumbnail-item.active .thumbnail-wrapper {
  border-color: #1a73e8;
  background: #1a73e8;
}

.thumbnail-image {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 1px;
  max-height: 150px;
  object-fit: contain;
}

.thumbnail-page-number {
  font-size: 12px;
  color: #9aa0a6;
  font-weight: 400;
}

.thumbnail-item.active .thumbnail-page-number {
  color: #e8eaed;
}

/* 分隔线 */
.sidebar-divider {
  width: 1px;
  background: #5f6368;
  flex-shrink: 0;
}

/* PDF内容区域 - 连续滚动 */
.pdf-content-area {
  flex: 1;
  background: #525659;
  overflow-y: auto;
  overflow-x: hidden;
}

.pdf-pages-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  gap: 20px;
}

.pdf-page-wrapper {
  display: flex;
  justify-content: center;
  width: 100%;
}

.pdf-page-image-container {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
  background: white;
  border-radius: 2px;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.pdf-page-image {
  display: block;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.pdf-page-image[src] {
  opacity: 1;
}

/* 滚动条样式 */
.sidebar-panel::-webkit-scrollbar,
.pdf-content-area::-webkit-scrollbar {
  width: 8px;
}

.sidebar-panel::-webkit-scrollbar-track,
.pdf-content-area::-webkit-scrollbar-track {
  background: #323639;
}

.sidebar-panel::-webkit-scrollbar-thumb,
.pdf-content-area::-webkit-scrollbar-thumb {
  background: #5f6368;
  border-radius: 4px;
}

.sidebar-panel::-webkit-scrollbar-thumb:hover,
.pdf-content-area::-webkit-scrollbar-thumb:hover {
  background: #80868b;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar-panel {
    width: 240px;
  }
  .top-toolbar {
    padding: 0 8px;
  }
  .pdf-info {
    display: none;
  }
  .toolbar-center {
    gap: 8px;
  }
}
</style>
